#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

""" Overload basic time stepper to handle early excercise. """

from numpy import sort, append, asarray

from DirichletTimeStepper import DirichletTimeStepper

class BermudamTimeStepper(DirichletTimeStepper):
    """
        Bermudam Options can be thuogh as European options with discrete
        and finite early exercise times.
    """
    __slots__ = ['m_exercise_dates']

    def __init__(self, method='cn'):
        """ instantaite an object of type BermudamTimeStepper."""

        DirichletTimeStepper.__init__(self, method)
        self.m_exercise_dates = None

    def set_exercise_dates(self, exer_dates):
        """ set early exercise dates. """

        self.m_exercise_dates = sort(asarray(exer_dates))

    def step(self):
        """ do time stepping acounting for early exercise dates."""

        if self.m_exercise_dates is None:
            return super(BermudamTimeStepper, self).step()

        exer_dates = self.m_exercise_dates
        expiry = self.get_expiry()
        assert exer_dates[-1] <= expiry

        if exer_dates[ -1] < expiry:
            exer_dates = append(exer_dates, expiry)

        if 0 == exer_dates[0]:
            exer_dates = exer_dates[1:]

        prev = 0
        self.set_number_steps(10)
        initial = self.get_initial_state().copy()
        tmp_solu = self.get_initial_state().copy()
        for i, exerd in enumerate(exer_dates):
            self.set_time2simulate(exerd, prev)
            if 0 < i:
                tmp = tmp_solu[1:-1]
                tmp[ tmp < initial ] = initial[ tmp < initial ]
                self.set_ival(tmp_solu[1:-1])

            tmp_solu = super(BermudamTimeStepper, self).step()
            prev = exerd
        return tmp_solu
